package main

import (
	"fmt"
	"io/ioutil"
	"os"
	"strconv"
	"time"
)

func main() {
	//var filename = "./output1.txt"
	//var f *os.File
	//var err1 error


	//data := []byte("XXX")
	file, err := os.OpenFile("output2.txt", os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0666)
	if err != nil {
		fmt.Println("open file failed, err:", err)
		return
	}
	defer file.Close()
	str := "hello 沙河"
	file.Write([]byte(str))       //写入字节切片数据
	file.WriteString("hello 小王子") //直接写入字符串数据
	go func() {
		for i := 0; i < 100; i++ {
			_, err1 := file.WriteString("---->"+strconv.Itoa(i))
			time.Sleep(time.Second)
			if err1 != nil {
				panic(err1)
			}
		}
	}()


	/*****************************  第二种方式: 使用 ioutil.WriteFile 写入文件 ***********************************************/

	bytes, err2 := ioutil.ReadFile("./output2.txt")
	fmt.Println(string(bytes))
	check(err2)
	time.Sleep(3* time.Second)

	fmt.Println("----------------------------------")
	bytes, err2 = ioutil.ReadFile("./output2.txt")
	fmt.Println(string(bytes))
	check(err2)
	time.Sleep(3* time.Second)

	fmt.Println("----------------------------------")
	bytes, err2 = ioutil.ReadFile("./output2.txt")
	fmt.Println(string(bytes))
	check(err2)
	time.Sleep(3* time.Second)


	fmt.Println("----------------------------------")
	bytes, err2 = ioutil.ReadFile("./output2.txt")
	fmt.Println(string(bytes))
	check(err2)
	time.Sleep(3* time.Second)

	fmt.Println("----------------------------------")
	bytes, err2 = ioutil.ReadFile("./output2.txt")
	fmt.Println(string(bytes))
	check(err2)
	time.Sleep(3* time.Second)

}


func check(e error) {
	if e != nil {
		panic(e)
	}
}

/**
 * 判断文件是否存在  存在返回 true 不存在返回false
 */
func checkFileIsExist(filename string) bool {
	var exist = true
	if _, err := os.Stat(filename); os.IsNotExist(err) {
		exist = false
	}
	return exist
}